package com.company.cloud.common.mq.redis.client.factory.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.StreamOperations;
import org.springframework.util.CollectionUtils;

import com.company.cloud.common.mq.redis.client.consumer.ISaasMqConsumer;
import com.company.cloud.common.mq.redis.client.consumer.annotation.MQRedisConsumer;
import com.company.cloud.common.mq.redis.client.factory.RedisMQClientFactory;
import com.company.cloud.common.mq.redis.client.producer.RedisMQProducer;

public class RedisMQSpringClientFactory  implements ApplicationContextAware, DisposableBean{

	private RedisMQClientFactory redisMQClientFactory;


	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		System.out.println("===================RedisMQSpringClientFactory ");
		List<ISaasMqConsumer> consumerList = new ArrayList<ISaasMqConsumer>();
		Map<String, Object> serviceMap = applicationContext.getBeansWithAnnotation(MQRedisConsumer.class);

		if (!CollectionUtils.isEmpty(serviceMap)) {
			for (Object serviceBean : serviceMap.values()) {
				if (serviceBean instanceof ISaasMqConsumer) {
					consumerList.add((ISaasMqConsumer) serviceBean);
				}
			}
		}
		
		StreamOperations<String, String, String> streamOperations= applicationContext.getBean("streamOperations", StreamOperations.class);
		this.redisMQClientFactory=new RedisMQClientFactory();
		this.redisMQClientFactory.setConsumerList(consumerList);
		this.redisMQClientFactory.setStreamOperations(streamOperations);
		this.redisMQClientFactory.init();
		RedisMQProducer.getInstall().setStreamOperations(streamOperations);
	}
	
	@Override
	public void destroy() throws Exception {
		this.redisMQClientFactory.destroy();
	}

}
